package com.jason.lightreader.controller;

import com.jason.lightreader.entity.Article;
import com.jason.lightreader.response.Code;
import com.jason.lightreader.response.Result;
import com.jason.lightreader.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    //根据文章id获取文章信息
    @GetMapping("/{articleID}")
    @PreAuthorize("permitAll()")
    public Result getArticleByID(@PathVariable Integer articleID) {
        return articleService.getArticleDetails(articleID);
    }

    //获取文库页数
    @GetMapping("/pages")
    @PreAuthorize("permitAll()")
    public Result getPageCount() {
        return articleService.getPageCount();
    }

    //根据页数获取文章
    @GetMapping("/page/{index}")
    @PreAuthorize("permitAll()")
    public Result getArticlesByPage(@PathVariable Integer index) {
        return articleService.getArticlesByPage(index);
    }

    //发布一篇文章
    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public Result publishArticle(@RequestParam("file") MultipartFile file, @RequestPart("article") Article article) {
        return articleService.addOneArticle(article, file);
    }

    //获取推荐文章
    @GetMapping("/recommend")
    @PreAuthorize("permitAll()")
    public Result getRecommendArticles(){
        return articleService.getRecommendArticle();
    }

    @GetMapping("/search")
    @PreAuthorize("permitAll()")
    public Result searchArticlesByTitle(@RequestParam String title){
        return articleService.searchArticlesByTitle(title);
    }
}
